
using System.Text;
using Furion.DatabaseAccessor;
using Furion.DistributedIDGenerator;

namespace SB2.Core;

public class SysObjectRepository : AppSugarRepository<SysObject>
{
    public SysObjectRepository(ISqlSugarClient context) : base(context)
    {
        base.Context = context;
    }
    public async Task<bool> InsertAsync(SysObjectCreateDto dto)
    {
        // 查询表结构
        var table = await GetByIdAsync(dto.TableId);
        var fileds = await GetListAsync(m => m.PId == table.ObjectId);
        var key = fileds.FirstOrDefault(m => m.Iskey);
        // 数据验证

        // 创建id
        if (key != null) dto.Data[key.ObjName] = BitConverter.ToInt64(IDGen.NextID().ToByteArray());
        // 插入

        await this.Context.Insertable(dto.Data).AS(table.ObjName).ExecuteCommandAsync();
        return true;
    }
    /// <summary>
    /// 新建表
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public async Task<bool> NewTabeAsync(SysObjectNewTableDto dto)
    {
        // 是否存在
        var table = (await GetListAsync(m => m.ObjName == dto.ObjName && m.PId == 0)).FirstOrDefault();
        if (table != null) throw Oops.Oh("表名已存在！");
        if (dto.Fileds != null && dto.Fileds.GroupBy(m => (m.ObjName + "").ToLower()).Any(m => m.Count() > 1))
            throw Oops.Oh("字段名重复");

        table = dto.Adapt<SysObject>().GetNewId();
        var items = new List<SysObject>();
        StringBuilder sb = new StringBuilder();
        items.Add(table);
        sb.AppendLine($"CREATE TABLE {table.GetName()}( ");
        var key = new SysObject { ObjName = "Id", PId = table.ObjectId, Des = "主键", DataType = SysObjectType.sBigInteger, Iskey = true }.GetNewId();
        items.Add(key);
        dto.Fileds?.ForEach(m =>
        {
            var f = m.Adapt<SysObject>().GetNewId();
            f.PId = table.ObjectId;
            items.Add(f);
            sb.AppendLine(f.GetSql());
            sb.Append(",");
        });
        sb.AppendLine($" Id BIGINT PRIMARY KEY ");
        sb.AppendLine(" ) ");
        // 插入数据 
        await this.InsertRangeAsync(items);
        // 创建表
        this.Context.Ado.SqlQuery<dynamic>(sb.ToString());
        return true;
    }
    /// <summary>
    /// 添加字段
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    public async Task<bool> NewFiledAsync(SysObjectNewFiledDto dto)
    {
        // 是否存在
        var table = (await GetListAsync(m => m.ObjectId == dto.PId && m.PId == 0)).FirstOrDefault();
        if (table == null) throw Oops.Oh("表不存在！");

        var f = dto.Adapt<SysObject>().GetNewId();
        var sql = $"ALTER TABLE {table.GetName()} ADD {f.GetSql()} ";
        // 插入数据 
        await this.InsertAsync(f);
        // 添加字段
        this.Context.Ado.SqlQuery<dynamic>(sql);
        return true;
    }

}
